<?php
/**
 * Created by PhpStorm.
 * User: khanhht
 * Date: 7/16/14
 * Time: 2:54 PM
 */

class My_Service_Server extends My_Service_Abstract {


    public function __construct(){
        parent::__construct();
        $this->_model = new Default_Model_Server();
    }

    /**
     * @param $gameId
     * @param null $userId
     * @param null $private true | false
     * @param null $openDate
     * @param null $closeDate
     * @return array|mixed
     */
    public function getServerGame($gameId, $userId = null,$private = null, $openDate = null, $closeDate = null){
        /* build cache key */
        $key = sprintf($this->_cache_key,md5(__CLASS__ . __FUNCTION__ . json_encode(func_get_args())));
        /* end build cache key */

        $result = $this->_memcache->get($key);
        if(!$result){
            if($userId){
                $kpiServer = new Default_Model_Server();
                $result = $kpiServer->getServerGame($gameId)->toArray();
                //chỉ lấy server riêng (exclude đi các server có trong channel khác mà user không có quyền)
                //pr($result);
                if($private){
                    $channelModel = new Default_Model_Channel();
                    $disabledChannel = $channelModel->getDisabledChannel($userId, $gameId);
                    $serverDisabled = array();
                    $channelServerModel = new Default_Model_Channelserver();
                    foreach($disabledChannel as $chn){
                        $serverDisabled += $channelServerModel->getServerChannelGame($gameId,$chn)->toArray();
                    }
                    //pr($serverDisabled);
                    $result = array_udiff($result,$serverDisabled,array($this,'compareServer'));
                }
            }else{ // get all server
                $result = $this->_model->getServerGame($gameId,$openDate,$closeDate)->toArray();
            }

            if($result){
                $this->_memcache->set($key,$result,false,0);
            }
        }
        return $result;

    }

    /**
     * Compare 2 server
     * @param array $server1
     * @param array $server2
     * @return int
     */
    private function compareServer(array $server1, array $server2){
        return strcmp ( $server1['serverId'] , $server2['serverId']);
    }

} 